<?php


namespace App\controllers\admin;


use App\controllers\Base;
use Consts\RedisKey;
use Helper\Config;
use Helper\Output;
use Helper\FileUploader;
use Helper\MagicCrypt;
use Helper\Mysql;
use Helper\Redis;
use Helper\Redis1;
use Imagine\Imagick\Imagine;
use Firebase\JWT\JWT;
use Inhere\Validate\Valid;
use Middleware\AuthMiddleware;

class Login extends Base
{

    public function doLogin($request, $response){

        $res = Mysql::getInstance()
            ->where('username',$request->post['username'])
            ->getOne('admin_user');
        if(!$res){
            return Output::json(1004);
        }

        if($res['password'] != md5($request->post['password'])){
            return Output::json(1005);
        }
        //禁止登录
        if($res['state'] != 1){
            return Output::json(1031);
        }
        if($res['platform_id']){
            $state = Mysql::getInstance()
                ->where('id',$res['platform_id'])
                ->getValue('platform','state');
            //平台被禁止
            if(!$state){
                return Output::json(1032);
            }
        }

        $jwtConf  = Config::getInstance()->get('jwt');
        $payload = array(
            "iss" => $jwtConf['iss'],
            "aud" => $jwtConf['aud'],
            "iat" => time(),
            "nbf" => time(),
            "exp" => time()+3600*24*7,
            "data"=> [
                'user_id'=> $res['id'],
                'user' => $res
            ]
        );

        unset($res['password']);

        $jwt = JWT::encode($payload, $jwtConf['key']);
        Redis::getInstance()->set(RedisKey::loginUserToken($res['id']),$jwt,RedisKey::LOGIN_SESSION_OUTTIME);

        Redis::getInstance()->set(RedisKey::user_authority_list($res['id']),json_encode(AuthMiddleware::getInstance()->getAuthority($res['role_id'])));

        $conf = Mysql::getInstance()->get('system_config');
        $conf = array_column($conf,'value_','key_name');
        return Output::json(200 ,['token'=> $jwt ,'user_info' => $res ,'conf'=> $conf]);

    }

    public function test($request, $response){





//        var_dump('res',$redis->set('test',1));
//        var_dump('ping',$redis->ping('111'));


    }

}